<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\model\goods\Goods as GoodsModel;
use app\api\model\hospital\Hospital as HospitalModel;
use app\api\model\hospital\HospitalDiscount;
use think\Db;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 计算下单金额
     */
    public function getCreateOrderInfo()
    {
        $ids = $this->request->post('ids/a');
        $goodsList = GoodsModel::where('id', 'in', $ids)->select();
        
        if (empty($goodsList)) {
            $this->error('检测项目不存在');
        }
        $user = $this->auth->getUser();
        if (empty($user->hospital_id)) {
            $this->error('请先绑定医院');
        }
        $hospital = HospitalModel::get($user->hospital_id);
        $hospitalDiscount = HospitalDiscount::where('hospital_id',$user->hospital_id)->where('goods_id','in',$ids)->select();
        $goodsDiscount = [];
        foreach ($hospitalDiscount as $item) {
            $goodsDiscount[$item->goods_id] = $item;
        }
        $totalPrice = 0;
        $price = 0;
        $rongqiList = [];
        $rongqiIds = [];
        $model = new \app\api\model\order\Order();
        foreach ($goodsList as &$goods) {
            $rongqi = $model->getRongqiList($goods);
            foreach ($rongqi as $rongqi_item) {
                $item = $rongqi_item->toArray();
                if($index = array_search($rongqi_item->id,$rongqiIds) === false){
                    $rongqiList[] = $item;
                    $rongqiIds[] = $rongqi_item->id;
                }
            }

            $discountPrice = ($goods->price * $hospital->discount / 100);
            if (isset($goodsDiscount[$goods->id])) {
                $discountPrice = $goodsDiscount[$goods->id]['type'] == 10 ? $goods->price * $goodsDiscount[$goods->id]['discount'] / 100  : $goodsDiscount[$goods->id]['money'];
            }
            $price +=  $discountPrice > 0 ? $discountPrice : 0.01;
            $totalPrice += $goods->price;
        }


        return $this->success('', [
            'price' => $price,
            'totalPrice' => $totalPrice,
            'goodsList' => $goodsList,
            'rongqiList'=>$rongqiList
        ]);
    }

    /**
     * 创建订单
     */
    public function createOrder()
    {
        // tubeData = [{'biaoben_rongqi_id'=>1,'tube_number'=>123456}]
        $tubeData = $this->request->post('tubeData/a');
        $goods_ids = $this->request->post('goods_ids/a',null);// 项目id
        $username = $this->request->post('username');
        $userphone = $this->request->post('userphone');
        $age = $this->request->post('age');
        $gender = $this->request->post('gender', 0) == 1 ? '男' : '女';

        if (empty($username)) {
            $this->error('患者姓名不能为空');
        }
        // if (empty($userphone)) {
        //     $this->error('患者手机号不能为空');
        // }
        if (!empty($userphone) && !preg_match('/^1[3-9]\d{9}$/', $userphone)) {
            $this->error('手机号格式错误');
        }
        if (empty($age)) {
            $this->error('患者年龄不能为空');
        }

        if (empty($tubeData) || count($tubeData) == 0) {
            $this->error('请选择检测项目');
        }
        $tubeList = [];
        $tube_number = [];

        foreach ($tubeData as $tube) {
            if(array_search($tube['tube_number'],$tube_number) !== false){
                $this->error("试管号‘{$tube['tube_number']}’重复");
            }
            $tube_number[] = $tube['tube_number'];
            $res = \app\api\model\order\OrderTube::where('tube_number',$tube['tube_number'])->with(['order'])->find();
            if ($res && $res['order']['pay_status'] == 1) {
                $this->error("试管号‘{$tube['tube_number']}’重复使用");
            }
        }

        $goodsList = GoodsModel::where('id', 'in', $goods_ids)->select();
        if (empty($goodsList)) {
            $this->error('检测项目不存在');
        }

        $user = $this->auth->getUser();
        if (empty($user->hospital_id)) {
            $this->error('请先绑定医院');
        }
        $hospital = HospitalModel::get($user->hospital_id);
        if($hospital->status == 10){
            $this->error('当前医院正在审核中,暂时不支持此操作');
        }
        $hospitalDiscount = HospitalDiscount::where('hospital_id',$user->hospital_id)->where('goods_id','in',$goods_ids)->select();
        $goodsDiscount = [];
        foreach ($hospitalDiscount as $item) {
            $goodsDiscount[$item->goods_id] = $item;
        }
        $totalPrice = 0;
        $price = 0;
        $rongqiList = [];
        $rongqiIds = [];
        $orderGoodsList = [];
        $goodsItemList = [];
        $saveOrderGoodsDetails = [];
        $model = new \app\api\model\order\Order();
        foreach ($goodsList as &$goods) {
            if($goods->type != 10){
                $temOrderGoodsDetails = \app\api\model\goods\GoodsDetails::field('goods_master_id,goods_id,type')->where('goods_master_id',$goods->id)->select();
                $saveOrderGoodsDetails = array_merge($saveOrderGoodsDetails,Collection($temOrderGoodsDetails)->toArray());
            }

            $rongqi = $model->getRongqiList($goods,$goodsItemList);
            foreach ($rongqi as $rongqi_item) {
                $item = $rongqi_item->toArray();
                if(array_search($rongqi_item->id,$rongqiIds) === false){
                    $rongqiList[] = $item;
                    $rongqiIds[] = $rongqi_item->id;
                }
            }
            $discountPrice = ($goods->price * $hospital->discount / 100);
            $discount_type = 30;
            $discount = $hospital->discount;
            if (isset($goodsDiscount[$goods->id])) {
                $discount_type = $goodsDiscount[$goods->id]['type'];
                $discount = $goodsDiscount[$goods->id]['discount'];
                $discountPrice = $goodsDiscount[$goods->id]['type'] == 10 ? $goods->price * $goodsDiscount[$goods->id]['discount'] / 100  : $goodsDiscount[$goods->id]['money'];
            }
            $_price = $discountPrice > 0 ? $discountPrice : 0.01;
            $price +=  $_price;
            $totalPrice += $goods->price;

            $orderGoodsList[] = [
                'type'=>$goods->type,
                'goods_id' => $goods->id,
                'goods_no'=> $goods->goods_no,
                'title' => $goods->title,
                'short_title' => $goods->short_title,
                'pinyin_title' => $goods->pinyin_title,
                'image' => $goods->image,
                'goods_category_id' => $goods->goods_category_id,
                'biaoben_type_id' => $goods->biaoben_type_id,
                'num' => $goods->num,
                'biaoben_rongqi_id' => $goods->biaoben_rongqi_id,
                'keshi' => $goods->keshi,
                'fangfa' => $goods->fangfa,
                'waijian_tags' => $goods->waijian_tags,
                'hospital' => $goods->hospital,
                'time' => $goods->time,
                'real_price' => $_price,
                'price' => $goods->price,
                'original_price' => $goods->original_price,
                'discount_type' => $discount_type,
                'discount' => $discount,
            ];
        }

        $saveGoodsItemList = [];
        foreach ($goodsItemList as $goods) {
            $saveGoodsItemList[] = [
                'type'=>$goods->type,
                'goods_id' => $goods->id,
                'goods_no'=> $goods->goods_no,
                'title' => $goods->title,
                'short_title' => $goods->short_title,
                'pinyin_title' => $goods->pinyin_title,
                'image' => $goods->image,
                'goods_category_id' => $goods->goods_category_id,
                'biaoben_type_id' => $goods->biaoben_type_id,
                'num' => $goods->num,
                'biaoben_rongqi_id' => $goods->biaoben_rongqi_id,
                'keshi' => $goods->keshi,
                'fangfa' => $goods->fangfa,
                'waijian_tags' => $goods->waijian_tags,
                'hospital' => $goods->hospital,
                'time' => $goods->time,
                'price' => $goods->price,
                'original_price' => $goods->original_price,
            ];
        }

        if(count($rongqiList) != count($tubeData)){
            $this->error('试管容器数量有误');
        }
        
        DB::startTrans();
        try {
            $orderMaster = new \app\api\model\order\OrderMaster();
            $order_sn = createOrdersn($user->id, 'O');
            $result = $orderMaster->save([
                'user_id' => $user->id,
                'sole_id' => $hospital->user_id,
                'hospital_id' => $user->hospital_id,
                'username' => $username,
                'userphone' => $userphone,
                'age' => $age,
                'gender' => $gender,
                'original_price' => $totalPrice,
                'price' => $price,
                'out_trade_no' => $order_sn,
                'order_sn' => $order_sn
            ]);
            if (!$result) {
                throw new \Exception('订单创建失败');
            }

            $tubeSaveList = [];
            foreach ($tubeData as $tube) {
                $tubeSaveList[] = [
                    'order_master_id' => $orderMaster->id,
                    'biaoben_rongqi_id' => $tube['biaoben_rongqi_id'],
                    'tube_number' => $tube['tube_number']
                ]; 
            }
            $orderTube = new \app\api\model\order\OrderTube();
            $orderTubeList = $orderTube->saveAll($tubeSaveList);
            if (!$orderTubeList) {
                throw new \Exception('订单创建失败');
            }
            
            foreach ($orderGoodsList as &$item) {
                $item['order_master_id'] = $orderMaster->id;
            }
            
            $orderGOods = new \app\api\model\order\OrderGoods();
            $orderGoodsListModel = $orderGOods->saveAll($orderGoodsList);
            if (!$orderGoodsListModel) {
                throw new \Exception('订单创建失败');
            }

            $saveGoodsItemListIds = [];
            $saveGoodsItemListData = [];
            foreach ($saveGoodsItemList as &$item) {
                $item['order_master_id'] = $orderMaster->id;
                if(!in_array($item['goods_id'],$saveGoodsItemListIds)){
                    $saveGoodsItemListIds[] = $item['goods_id'];
                    $saveGoodsItemListData[] = $item;
                }
            }
            $orderGoodsItem = new \app\api\model\order\OrderGoodsItem();
            $orderGoodsItemListModel = $orderGoodsItem->saveAll($saveGoodsItemListData);
            if (!$orderGoodsItemListModel) {
                throw new \Exception('订单创建失败');
            }

            if(count($saveOrderGoodsDetails)){
                foreach ($saveOrderGoodsDetails as &$item) {
                    $item['order_master_id'] = $orderMaster->id;
                }
                $orderGoodsDetails = new \app\api\model\order\OrderGoodsDetails();
                $orderGoodsDetailsListModel = $orderGoodsDetails->saveAll($saveOrderGoodsDetails);
                if (!$orderGoodsDetailsListModel) {
                    throw new \Exception('订单创建失败');
                }
            }
            
            
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            $this->error($e->getMessage());
        }

        $this->success('', [
            'id' => $orderMaster->id
        ]);
    }

    public function orderPay()
    { 
        $id = $this->request->post('id');
        $payType = $this->request->post('payType',10);
        $model = \app\api\model\order\OrderMaster::get($id);
        $user = new \app\api\model\User();
        $user = $user::get($model->user_id);
        if (!$model) {
            $this->error('订单不存在');
        }
        if ($model->user_id != $user->id) {
            $this->error('订单不属于当前用户');
        }
        if ($model->pay_status == 1) {
            $this->error('订单已支付,请勿重复操作');
        }

        $orderGoodsModel = new \app\api\model\order\OrderGoods();
        $orderGoodsList = $orderGoodsModel::where(['order_master_id' => $model->id])->select();

        $goodsTitle = [];
        foreach ($orderGoodsList as $orderGoods) {
            $goodsTitle[] = $orderGoods->title;
        }
        $goodsTitle = implode(',', $goodsTitle);

        if ($payType == 10) { 
            if($model->price > $user->money){
                $this->error('余额不足');
            }
            DB::startTrans();
            try {
                
                $user->setUpdateMoneyParams(["memo"=>"购买检测项目：{$goodsTitle}","gift_money"=>0,'title'=>'支出金额','datatype'=>20]);
                $user->money = $user->money - $model->price;
                $result = $user->save();
                if(!$result){
                    throw new \Exception('支付失败');
                }
                $model->pay_status = 1;
                $model->status = 10;
                $model->pay_type = 10;
                $model->pay_time = time();
                $result = $model->save();
                if(!$result){
                    throw new \Exception('支付失败');
                }

                $resultPatient = \app\api\model\Patient::get([
                    'doctor_id'=>$model->user_id,
                    'hospital_id'=>$model->hospital_id,
                    'username'=>$model->username,
                    'age'=>$model->age,
                    'gender'=>$model->gender,
                ]);
                if(!$resultPatient){
                    $patient = new \app\api\model\Patient();
                    $patient->doctor_id = $model->user_id;
                    $patient->hospital_id = $model->hospital_id;
                    $patient->username = $model->username;
                    $patient->userphone = $model->userphone;
                    $patient->age = $model->age;
                    $patient->gender = $model->gender;
                    $patient->save();
                }

                
                foreach ($orderGoodsList as $orderGoods) {
                    $order = new \app\api\model\order\Order();
                    $result = $order->save([
                        'order_master_id'=>$model->id,
                        'order_goods_id'=>$orderGoods->id,
                        'user_id'=>$model->user_id,
                        'sole_id'=>$model->sole_id,
                        'hospital_id'=>$model->hospital_id,
                        'username'=>$model->username,
                        'userphone'=>$model->userphone,
                        'age'=>$model->age,
                        'gender'=>$model->gender,
                        'out_trade_no'=>$model->out_trade_no,
                        'transaction_id'=>$model->transaction_id,
                        'order_sn'=>createOrdersn($model->user_id,'S'),
                        'price'=>$orderGoods->real_price,
                        'original_price'=>$orderGoods->price,
                        'pay_type'=>$model->pay_type,
                        'order_type'=>10,
                        'pay_status'=>1,
                        'pay_time'=>time(),
                        'status'=>10,
                    ]);

                    if (!$result) {
                        \think\Log::record("子订单保存失败：{$order->out_trade_n}-{$orderGoods->id}");
                        throw new \Exception("子订单保存失败：{$order->out_trade_n}-{$orderGoods->id}");
                    }else{
                        $orderGoods->order_id = $order->id;
                        $orderGoods->save();
                    }
            }

            } catch (\Exception $e) { 
                DB::rollback();
                $this->error($e->getMessage());
            }
            DB::commit();
            $this->success('支付成功', []);
        }else{
            try{
                $pay = new \addons\epay\library\Service();
                $request = request();
                $notifyurl =  $request->root(true) . '/api/notifyx/notifyxOrder/paytype/wechat';
                $result = $pay->submitOrder([
                    'amount'    => ($model->price),
                    'orderid'   => $model->out_trade_no,
                    'type'      => 'wechat',
                    'title'     => "购买检测项目：{$goodsTitle}",
                    'notifyurl' => $notifyurl,
                    'returnurl' => '',
                    'method'    => 'miniapp',
                    'openid'    => $user->openid,
                    'custom'    => [],
                ]);
            } catch (\Exception $e) { 
                $this->error($e->getMessage());
            }
            
            $this->success('', $result);
        }
        
    }

    /** 
     * 医生获取订单列表
     */
    public function getOrderList()
    { 
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $status = $this->request->post('status', '');
        $report_status = $this->request->post('report_status', '');
        $datetime = $this->request->post('datetime/a', '');
        $title = $this->request->post('title', '');

        $user = $this->auth->getUser();
        $where = [
            'pay_status'=>1,
            'user_id'=>$user->id
        ];
        if ($report_status) {
            $where['report_status'] = $report_status;
            $where['status'] = 30;
        }else{
            if ($status) {
                $where['status'] = $status;
                if($status==30){
                    // 已送检
                    $where['status'] = 30;
                    $where['report_status'] = 10;
                }else if($status==40){
                    // 检测中
                    $where['status'] = 30;
                    $where['report_status'] = 20;
                }else if($status==50){
                    // 检测部分完成
                    $where['status'] = 30;
                    $where['report_status'] = 25;
                }else if($status==60){
                    // 检测完成
                    $where['status'] = 30;
                    $where['report_status'] = 30;
                }
            }
        }
        if ($datetime) {
            $where['order.createtime'] = ['between',[strtotime($datetime[0].' 00:00:00'),strtotime($datetime[1].' 23:59:59')]];
        }
        // if ($title) {
        //     $where['order_goods.title'] = ['like', '%'.$title.'%'];
        // }
        

        $order = new \app\api\model\order\OrderMaster();
        $list = $order->alias("order")
                    ->field("order.*")
                    ->where($where)
                    ->order('id', 'desc')
                    ->with(['ordergoods','hospital'])
                    ->paginate($limit, false, ['page' => $page]);
        $this->success('', $list);
        
    }


    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error("参数错误");
        }
        $order = \app\api\model\order\OrderMaster::with(['ordergoods','orderReport','orderTube','hospital2'])->find($id);
        if (!$order) {
            $this->error("订单不存在");
        }
        // $orderTube = \app\api\model\order\OrderTube::with(['biaobenRongqi'])->where('id','in',$order['ordergoods']['order_tube_id'])->select();
        // $order['order_tube'] = $orderTube;
        $this->success('', $order);
    }
}
